package com.tianya.forum.interceptor;

import com.tianya.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    // 从配置⽂件中获取默认登录⻚的URL
    @Value("${tianya-forum.login.url}")
    private String dafaultURL;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取⽤⼾session, 并判断⽤⼾是否登录
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppConfig.USER_SESSION) != null){
            return true;
        }

        // 没有登录强制跳转到登录⻚⾯
        response.sendRedirect(dafaultURL);
        return false;
    }
}